<?php

namespace App\Http\Controllers\Invoice\Merchant;

use App\Enums\Check\CheckEnum;
use App\Http\Controllers\BaseController;
use App\Models\Invoice\InvoiceHistoryModel;
use App\Remote\Orm\OrmNewOrderRemote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class IndexController extends BaseController
{

    /**
     * 根据门店查询订货可开票订单
     * @param Request $request
     * @return JsonResponse
     */
    public function orderList(Request $request): JsonResponse
    {
        $shopId  = (int)$request->header('shopId', 0);
        $sysType = (int)$request->get('sysType', 0);
        $day     = -93;//订单订单范围，当前日期，往前推一个季度（按照一个月 31 天，即 93 天范围）
        switch ($sysType) {
            case InvoiceHistoryModel::BUSINESS_TYPE_1:// 商家app订货 + 设备费
                $sysType = implode(',', [CheckEnum::SYS_TYPE_ROS, CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT]);
                break;
            case InvoiceHistoryModel::BUSINESS_TYPE_2:// 软装
                $sysType = CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE;
                break;
        }

        $ormOrderList = OrmNewOrderRemote::getNewOrderByShopId(
            $shopId, $day, $sysType, OrmNewOrderRemote::NEW_ORDER_STATUS_FINISH, OrmNewOrderRemote::INVOICE_STATUS_NOT, '0'
        );

        $data = [];
        collect($ormOrderList['data'] ?? [])
            ->where('pay_amount', '>', 0)// 支付金额大于0
            ->where('need_pay', '>', 0)  // 非直营店
            ->map(
                function ($item) use (&$data) {
                    $data[date('Y-m', strtotime($item['create_time']))][] = [
                        "id"         => $item['id'],
                        "code"       => $item['code'],
                        "createTime" => $item['create_time'],
                        "payAmount"  => bcdiv($item['pay_amount'] - $item['payment_fee'], 1, 2),// 支付金额-手续费
                    ];
                }
            );
        return $this->success($data);
    }
}
